import { defineStore } from 'pinia';
import type { UserState } from '@/stores/modules/user/types.ts';
import type { LoginForm, RegisterForm, UpdateForm } from '@/api/portal/types.ts';
import { login, register, updateProfile } from '@/api/portal';
import Message from '@/components/message';
import { useCommentStore } from '@/stores';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: undefined,
    avatar: undefined,
    email: undefined,
    nickname: undefined,
    status: undefined,
    isAdmin: undefined,
    signature: undefined,
  }),

  getters: {
    // 判断是否登录 - 这里用 email 判断很好，因为邮箱是必填且唯一的
    isLoggedIn: (state) => {
      return !!state.email;
    },

    // 可以添加一些其他有用的 getter
    userNickname: (state) => {
      return state.nickname || state.email?.split('@')[0] || '用户'; // 如果没有昵称，显示邮箱前缀或默认名
    }
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo: UserState) {
      this.id = userInfo.id;
      this.isAdmin = userInfo.isAdmin;
      this.avatar = userInfo.avatar;
      this.email = userInfo.email;
      this.nickname = userInfo.nickname;
      this.status = userInfo.status;
      this.signature = userInfo.signature;
    },

    // 清除用户信息（可以添加）
    clearUserInfo() {
      this.avatar = undefined;
      this.email = undefined;
      this.nickname = undefined;
      this.status = undefined;
      this.id = undefined;
      this.isAdmin = undefined;
      this.signature = undefined;
    },

    // 登录
    async login(loginForm: LoginForm) {
      try {
        const { data } = await login(loginForm);
        this.setUserInfo(data);
        this.setCommentRefresh();
        Message.success('登录成功');
        return data;
      } catch (err) {
        throw err;
      }
    },

    // 注册
    async register(registerForm: RegisterForm) {
      try {
        const { data } = await register(registerForm);
        this.setUserInfo(data);
        this.setCommentRefresh();
        Message.success('注册成功');
        return data;
      } catch (err) {
        throw err;
      }
    },

    async updateProfile(updateForm:UpdateForm) {
      try {
        await updateProfile(updateForm);
        await this.updateAvatar(updateForm.avatar);
        this.nickname = updateForm.nickname;
        this.signature = updateForm.signature;
        Message.success('保存成功');
      } catch (err) {
        throw err;
      }
    },

    async updateAvatar(avatarUrl:string){
      this.avatar = avatarUrl;
    },

    // 设置刷新
    setCommentRefresh(){
      const commentStore = useCommentStore();
      commentStore.setNeedRefresh(true);
    },

    // 退出登录（可以添加）
    logout() {
      this.clearUserInfo();
      this.setCommentRefresh();
      Message.success('已退出登录');
    }
  },

  persist: {
    key: 'portal-user',
    storage: localStorage,
  },
});

export default useUserStore;
